﻿using System;
using System.ComponentModel.Composition;
using System.Windows;
using Caliburn.Micro;

namespace Zero.Frontend
{
    /// <summary>
    /// Allows showing and hiding busy indicatior in coroutine.
    /// </summary>
    public class BusyResult : IResult
    {
        private readonly bool _isBusy;
        private readonly object _busyViewModel;

        /// <summary>
        /// The Constructor
        /// </summary>
        /// <param name="isBusy">Mark as busy or not.</param>
        /// <param name="busyViewModel">The concerned ViewModel.
        /// If null, the <see cref="ActionExecutionContext"/>-Target is taken.</param>
        public BusyResult(bool isBusy, object busyViewModel = null)
        {
            _isBusy = isBusy;
            _busyViewModel = busyViewModel;
        }

        void IResult.Execute(ActionExecutionContext context)
        {
            var sourceViewModel = _busyViewModel ?? context.Target;

            if (_isBusy)
                IoC.Get<IBusyService>().MarkAsBusy(sourceViewModel, null);
            else
                IoC.Get<IBusyService>().MarkAsNotBusy(sourceViewModel);

            _completed(this, new ResultCompletionEventArgs());
        }

        private EventHandler<ResultCompletionEventArgs> _completed = delegate { };
        event EventHandler<ResultCompletionEventArgs> IResult.Completed
        {
            add { _completed += value; }
            remove { _completed -= value; }
        }
    }
}
